package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String WX_Login = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;


    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //用前端实体类获得授权码 调用方法使用授权码获取开放ID --->因为开放平台所以是开放id --->open
        String openId = getOpenId(userLoginDTO.getCode());
        //丰富逻辑，后台如果没有openid 要么数据有误，要么是未注册账号
        if (openId==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //未注册账号，将调用方法注册账号
        User user = userMapper.getByOpenId(openId);
        //注册空值判断
        if (user==null){
            user = User.
                    builder().
                    openid(openId).
                    createTime(LocalDateTime.now()).
                    build();
            //录入数据库
            userMapper.insert(user);
        }
        return user;
    }

    private String getOpenId(String code){
        //调用接口 从字段中获取信息 使用参数获取openid
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grand_type","authorization_code");
        //工具类
        String json = HttpClientUtil.doGet(WX_Login, map);
        //数据转换为JSON对象
        JSONObject jsonObject = JSON.parseObject(json);
        //从JSON对象中
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
